package com.yy.myp;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.yy.myp.activity.MapActivity;
import com.yy.myp.adapter.MainCardItemAdapter;
import com.yy.myp.provider.MockLocationProvider;
import com.yy.myp.utils.AlertUtils;

import java.util.Arrays;
import java.util.stream.Collectors;

public class MainActivity extends AppCompatActivity {

    private MockLocationProvider mock;

    private final int LOCATION_REQUEST_CODE = 1;

    private RecyclerView recViewPositions;

    private MainCardItemAdapter mainCardItemAdapter;

    private Button btnStart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 1024);
            }
        }
        setContentView(R.layout.activity_main);

        try {
            mock = new MockLocationProvider(Arrays.asList(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER), this);
        } catch (Exception e) {
            Log.v("Tag", "失败: e", e);
//            Toast.makeText(this, "请在开发者选项中设置模拟位置信息应用2", Toast.LENGTH_SHORT).show();
            AlertUtils.alertMessage(this, "请在开发者选项中设置模拟位置信息应用", null);
            return;
        }
        LocationManager locMgr = (LocationManager)
                getSystemService(LOCATION_SERVICE);
        LocationListener lis = location -> {
            //You will get the mock location
            Log.v("LOG",String.format("get the mock location: <%s, %s>", location.getLatitude(), location.getLongitude()));
        };

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
            }, LOCATION_REQUEST_CODE);
            Log.v("LOG","request location request error");
            AlertUtils.alertMessage(this, "请在开发者选项中设置模拟位置信息应用", null);
            return;
        }
        locMgr.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 1000, 1, lis);

        Button btnCreatePosition = findViewById(R.id.btn_create_position);
        btnCreatePosition.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, MapActivity.class);
            startActivityForResult(intent, 0);
        });

        recViewPositions = findViewById(R.id.rec_view_positions);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recViewPositions.setLayoutManager(linearLayoutManager);
        mainCardItemAdapter = new MainCardItemAdapter(this);
        recViewPositions.setAdapter(mainCardItemAdapter);

        mainCardItemAdapter.setOnItemClickListener( pointCard -> {
            LatLng latLng = new LatLng(pointCard.getLatitude(), pointCard.getLongitude());
            mock.pushLocation(latLng);
        });

        btnStart = findViewById(R.id.btn_start);
        btnStart.setOnClickListener( v -> {
            Log.v("TAG", "I click the start button");
            if (!mock.isRunning()) {
                if (mock.startMock()) {
                    btnStart.setText("停止");
                } else {
                    Toast.makeText(this, "请选择需要模拟的地点！", Toast.LENGTH_SHORT).show();
                }
            } else {
                btnStart.setText("开始");
                mock.stopMock();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            int localPosId = bundle.getInt("localPosId");
            Log.v("TAG", String.format("添加地址：数据库存储 %s", localPosId));

            mainCardItemAdapter.addPosition(localPosId);
            recViewPositions.scrollToPosition(mainCardItemAdapter.getItemCount() - 1);
            return;
        }
        if (requestCode == 1024) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (!Environment.isExternalStorageManager()) {
//                    Toast.makeText(this, "暂无文件权限，程序无法运行！", Toast.LENGTH_SHORT).show();
                    AlertUtils.alertMessage(this, "暂无文件权限，程序无法运行！", null);
                }
            }
            return;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_REQUEST_CODE) {
            Log.v("LOG", "permission: " + Arrays.stream(permissions).collect(Collectors.joining()));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mock.shutdown();
    }
}